package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ImageActivity extends AppCompatActivity {
    private static final int TAKE_PHOTO = 11;
    private static final int CROP_PHOTO = 12;
    private static final int LOCAL_CROP = 13;

    private Button btn_select;
    private ImageView iv_pic;
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);
        setViews();
        setListeners();

    }

    /*
     *设置监听
     */
    private void setListeners() {
        btn_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhotoOrSelectPicture();
            }
        });
    }

//    private File createImageFile() {
//        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//        String imageFileName = "JPEG_" + timeStamp + "_";
//        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        File imageFile = null;
//        try {
//            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return imageFile;
//    }

    private void takePhotoOrSelectPicture() {
        CharSequence[] items = {"拍照", "图库"};

        new AlertDialog.Builder(ImageActivity.this)
                .setItems(items, new DialogInterface.OnClickListener() {
                    @SuppressLint("QueryPermissionsNeeded")
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
//                                Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
//                                if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
//                                    File imageFile = createImageFile();//创建用来保存照片的文件
//                                    if (imageFile != null) {
//                                        imageUri = Uri.fromFile(imageFile);
//                                        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将用于输出的文件Uri传递给相机
//                                        startActivityForResult(takePhotoIntent, TAKE_PHOTO);//打开相机
//                                    }
//                                }


//                                File takePhotoImage = new File(Environment.getExternalStorageDirectory(),"take_photo_image.jpg");
//                                try {
//                                    if(takePhotoImage.exists()){
//                                        takePhotoImage.delete();
//                                    }
//                                    takePhotoImage.createNewFile();
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                                imageUri = Uri.fromFile(takePhotoImage);
                                Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                if(takePhotoIntent.resolveActivity(getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
                                    startActivityForResult(takePhotoIntent,TAKE_PHOTO);//启动相机
                                }

//                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//用来打开相机的Intent
//                                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
//                                if(intent.resolveActivity(getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
//                                    startActivityForResult(intent,TAKE_PHOTO);//启动相机
//                                }
//                                startActivityForResult(intent,);
                                break;
                            case 1:
                                Intent intent1 = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(intent1, LOCAL_CROP);
                                break;
                        }
                    }
                }).show();
    }

    private void setViews() {
        btn_select = (Button) findViewById(R.id.btn_select);
        iv_pic = (ImageView) findViewById(R.id.iv_pic);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
//                    Intent intent = new Intent("com.android.camera.action.CROP");
//                    intent.setDataAndType(imageUri, "image/*");
//                    intent.putExtra("scale", true);
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                    startActivityForResult(intent, CROP_PHOTO);

                    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//用来打开相机的Intent
                    if(takePhotoIntent.resolveActivity(getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
                        startActivityForResult(takePhotoIntent,CROP_PHOTO);//启动相机
                    }
                }
                break;
            case LOCAL_CROP:
                if (resultCode == RESULT_OK) {
                    Intent intent1 = new Intent("com.android.camera.action.CROP");
                    Uri uri = data.getData();
                    intent1.setDataAndType(uri, "image/*");
                    intent1.putExtra("outputX", 300);
                    intent1.putExtra("return-data", true);
                    startActivityForResult(intent1, CROP_PHOTO);
                }
                break;
            case CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (imageUri != null) {
//                        try {
//                            /*如果拍照成功，将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
//                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                            iv_pic.setImageBitmap(bitmap);//显示到ImageView上
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        }


                        Bundle extras = data.getExtras();
                        Bitmap bitmap = (Bitmap) extras.get("data");
                        iv_pic.setImageBitmap(bitmap);


//                        try {
//                            BitmapFactory.Options option = new BitmapFactory.Options();
//                            option.inSampleSize = 2;
//                            option.inPreferredConfig = Bitmap.Config.RGB_565;
//                            Bitmap bitmap = null;
//                            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, option);
//                            iv_pic.setImageBitmap(bitmap);
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        }

                    }
                    if (data != null) {
                        Bitmap bitmap = data.getExtras().getParcelable("data");
                        iv_pic.setImageBitmap(bitmap);
                    }
                }
                break;


        }
//        super.onActivityResult(requestCode, resultCode, data);
    }
}
